import 'package:fate_blind_box/ui/login/personinformation/personinformation_zero.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:flutter/material.dart';
import '../../../network/Api.dart';
import '../../../theme/theme_color.dart';
import '../../../utils/loading.dart';
import '../../../utils/provider.dart';
import 'logoutNext.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class MeAccountSafeUI extends StatelessWidget {
  const MeAccountSafeUI({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _MeAccountSafeUIWidget();
  }
}

class _MeAccountSafeUIWidget extends StatefulWidget {
  const _MeAccountSafeUIWidget({Key? key}) : super(key: key);

  @override
  State<_MeAccountSafeUIWidget> createState() => _MeAccountSafeUIWidgetState();
}

class _MeAccountSafeUIWidgetState extends State<_MeAccountSafeUIWidget> {
  final List _listData = [
    {'title': '绑定手机号'},
    {
      'title': '绑定微信',
    },
  ];

  String mobile = '';
  int bind = 0;
  bool isAuth = false;

  @override
  void initState() {
    super.initState();

    _meActSafe();
  }

  // @override
  // void initState() {}

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      title: '账号与安全',
      childWidget: Container(
        child: _buildContent(),
      ),
    );
  }

  _meActSafe() async {
    final res = await Api.getInstance().accountSecure();
    final data = res['data'];

    if (res['code'] == 0 && res['data'] != null) {
      setState(() {
        if (data['mobilePhone'] != null) {
          mobile = data['mobilePhone'];
        }
        Provider.mobile = mobile;
        bind = data['bind'];
      });
    }
  }

  Widget _buildContent() {
    return Container(
      color: Colors.white,
      height: 200,
      margin: const EdgeInsets.only(top: 0),
      child: Column(children: [
        _buildActionButton(
          _listData[0]['title'],
          mobile,
          0,
        ),
        const Divider(thickness: 1.0),
        _buildActionButton(
          _listData[1]['title'],
          bind == 0 ? '未绑定' : '已绑定',
          1,
        ),
        const Divider(thickness: 5.0),
        SizedBox(
          height: 56,
          child: GestureDetector(
              onTap: () {
                //注销APP
                Navigator.of(context).push(
                    MaterialPageRoute(builder: (ctx) => const logoutNextUI()));
              },
              child: const Center(
                child: Text(
                  '注销账号',
                  style: TextStyle(color: Colors.red, fontSize: 16),
                ),
              )),
        )
      ]),
    );
  }

  Widget _buildActionButton(String title, String subTitle, int index) {
    return GestureDetector(
        onTap: () {
          _onClick(index);
        },
        child: Container(
          height: 56,
          margin: const EdgeInsets.symmetric(horizontal: 12),
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const SizedBox(
                    width: 5,
                  ),
                  Text(
                    title,
                    style: TextStyle(color: ThemeColor.textColor, fontSize: 15),
                  ),
                ],
              ),
              Row(
                children: [
                  _buildActionSwitch(subTitle),
                  _buildActionArrow(leftTitle: title),
                ],
              ),
            ],
          ),
        ));
  }

  void _onClick(int index) {
    switch (index) {
      case 0:
        //绑定手机号
        if (mobile == 'null' || mobile.isEmpty || mobile == null) {
          Navigator.of(context)
              .push(MaterialPageRoute(
                  builder: (builder) =>
                      const PersonInformationZeroPageWidget('设置手机号')))
              .then((value) => _meActSafe());
        }else{
          toast('您已绑定手机号，无需绑定');
        }
        break;
      case 1:
        //绑定微信
        if (bind == 0) {
          _bindWechat();
        }else{
          toast('您已绑定微信，无需绑定');
        }
        break;
    }
  }

  _bindWechat() {
    fluwx.sendWeChatAuth(
        scope: "snsapi_userinfo", state: 'wechat_sdk_demo_test');
    _wechatCallbackss();
  }

  void _wechatCallbackss() {
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (isAuth) return;
      if (res is fluwx.WeChatAuthResponse) {
        print(
            'ffff ${res.code} \n${res.type} \n${res.state} \n${res.country}  \n${res.lang} \n${res.errStr} \n${res.errCode} \n${res.isSuccessful}');
        String? code = res.code;
        if (res.isSuccessful) {
          print('ddddd ${Provider.memberId}');
          _bindWechatServer(code!, Provider.memberId);
        } else {
          toast(res.errStr ?? "微信授权绑定失败[${res.errCode}]");
        }
      }
    });
  }

  void _bindWechatServer(String code, String memberId) {
    isAuth = true;
    loading(() async {
      final res = await Api.getInstance().bindWechat(code, memberId);
      if (res['code'] == 0) {
        _meActSafe();
      }
      toast(res['msg']);
    });
  }

  ///是否显示switch
  Widget _buildActionSwitch(String subTitle) {
    return InkWell(
      child: Row(
        children: [
          Container(
            margin: const EdgeInsets.only(right: 5),
            child: Text(
              subTitle,
              style: TextStyle(fontSize: 12, color: ThemeColor.textColorSecond),
            ),
          ),
        ],
      ),
    );
  }

  ///显示箭头
  Widget _buildActionArrow({String leftTitle = ''}) {
    return Visibility(
      visible: isNeedHiddenArrow(leftTitle),
      child: Icon(
        Icons.arrow_forward_ios,
        color: ThemeColor.textColorSecond,
        size: 15,
      ),
    );
  }

  bool isNeedHiddenArrow(String leftTitle) {
    if (leftTitle.contains('手机号')) {
      if (mobile.isNotEmpty) {
        return false;
      }
      return true;
    }

    if (leftTitle.contains('微信')) {
      if (bind == 1) {
        return false;
      }
      return true;
    }

    return true;
  }
}
